package com.java.util;

import com.java.util.pojo.User;

import java.util.*;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * list集合分组然后内部集合排序，并基于map-key排序
 */
public class ListGroupMapListSort {
    public static final String SINGLE_VARIANT = "$singleVariant";

    public static void main(String[] args) {

        List<User> voList = new ArrayList<>();

        voList.add(new User(1, "ss", "single", 222, true));


        voList.add(new User(2, "zz", "上海", 222, false));
        voList.add(new User(3, "ww", "上海", 222, false));
        voList.add(new User(4, "yy", "北京", 333,false));
        voList.add(new User(5, "cc", "北京", 333, false));
        voList.add(new User(6, "ii", "成都", 444, false));
        voList.add(new User(7, "kk", "成都", 444, false));

        Map<String, List<User>> resultMap = voList.stream()
                .collect(Collectors.groupingBy(
                        e -> {

                            return Objects.equals(e.getStatus(), Boolean.TRUE) ? SINGLE_VARIANT : e.getCity();


                        },
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                list -> list.stream()
                                        .sorted(Comparator.comparing(User::getName, Comparator.nullsLast(Comparator.naturalOrder())))
                                        .collect(Collectors.toList())
                        )
                ));

        // 按照key降序
//        TreeMap<String, List<User>> treeMapRes = new TreeMap<>(Comparator.reverseOrder());

        // 默认升序
        TreeMap<String, List<User>> treeMapRes = new TreeMap<>();

        treeMapRes.putAll(resultMap);

        System.out.println(">>>>>> ");

        /*Map<String, List<User>> unsortedMap = new HashMap<>();
        Map<String, List<User>> sortedMap = unsortedMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey()) // 对entry的key进行排序
                .collect(Collectors.toMap(
                        Map.Entry::getKey, // keyMapper
                        entry -> entry.getValue().stream() // 对每个List进行排序
                                .sorted(Comparator.comparing(User::getName))
                                .collect(Collectors.toList()), // 收集排序后的List
                        (oldValue, newValue) -> oldValue, // mergeFunction，这里假设key是唯一的
                        TreeMap::new // 使用TreeMap保持顺序
                ));*/
    }
}
